package com.simafei.flow.web.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 通用参数填充实现类
 * <p>
 * 如果没有显式的对通用参数进行赋值，这里会对通用参数进行填充、赋值
 *
 * @author hexiaowu
 */
@Component
public class DefaultDbFieldHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BasePO base) {

            LocalDateTime current = LocalDateTime.now();
            // 创建时间为空，则以当前时间为插入时间
            if (Objects.isNull(base.getCreateTime())) {
                base.setCreateTime(current);
            }
            // 更新时间为空，则以当前时间为更新时间
            if (Objects.isNull(base.getUpdateTime())) {
                base.setUpdateTime(current);
            }
            String operator = operator();
            if (Objects.isNull(base.getCreator())) {
                base.setCreator(operator);
            }
            if (Objects.isNull(base.getUpdater())) {
                base.setUpdater(operator);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        Object updater = getFieldValByName("updater", metaObject);
        if (Objects.isNull(updater)) {
            String operator = operator();
            setFieldValByName("updater", operator, metaObject);
        }
    }

    private String operator() {
        //TODO 集成登录后，从上下文中获取当前操作人
        return "System";
    }
}
